package com.wuze.cloud.util;

import com.wuze.cloud.enums.SysBooleanEnum;
import com.wuze.cloud.exception.SysGlobalException;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static com.wuze.cloud.enums.SysGlobalExceptionEnum.UPLOAD_ERR;

/**
 * @author: wuze
 * @description:
 * @date: 2023/02/18
 */
public class ShardToMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    private static final String KEY = "qwertyuiopoiuytr";
    private static final String VI = "poiuytrewqwertyu";

    public ShardToMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        // TODO - implementation depends on your requirements
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        // TODO - implementation depends on your requirements
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

    public static MultipartFile shardToMultipart(String shard, Integer encrypt) {
        try {
            String base64 = "";
            if(SysBooleanEnum.TRUE.getCode().equals(encrypt)){
                base64 = decrypt(shard, KEY, VI);
            }else{
                base64 = shard;
            }
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            return new ShardToMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());

        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        } catch (BadPaddingException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new SysGlobalException(UPLOAD_ERR.getCode(),UPLOAD_ERR.getMsg());
        }
    }

    public static String decrypt(String encryptedData, String key, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedData.getBytes());
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
